﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AIC_PN
{
    public partial class FormVanBanDieuHanh : System.Web.UI.Page
    {
        private static int ID;
        private static string FilePath = "";
        private static int LoaiVanBan = -1;
        #region Ham chuc nang

        protected void InsertData()
        {
            try
            {
                string sql = "INSERT INTO dbo.tblTaiLieu(TaiLieuID1_DM,TaiLieuID2_DM,TaiLieuID3_DM,TaiLieuID4_DM,TaiLieuID5_DM,TaiLieuID6_DM,SoHieu ,TenTaiLieu ,NgayBanHanh ,HieuLucTu ,HieuLucDen ,TrichYeu ,NoiDung ," +
                         "FileDinhKem ,CreateDate ,UpdateDate ,UserID) VALUES(@TaiLieuID1_DM,@TaiLieuID2_DM,@TaiLieuID3_DM,@TaiLieuID4_DM,@TaiLieuID5_DM,@TaiLieuID6_DM,@SoHieu,@TenTaiLieu,@NgayBanHanh,@HieuLucTu," +
                         "@HieuLucDen,@TrichYeu,@NoiDung,@FileDinhKem,GETDATE(),GETDATE(),@UserID)";
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@TaiLieuID1_DM", SqlDbType.Int, ParameterDirection.Input, LoaiVanBan));
                arrParams.Add(SqlHelper.CreateParameterObject("@TaiLieuID2_DM", SqlDbType.Int, ParameterDirection.Input, ddlTaiLieuID2_DMFNew.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@TaiLieuID3_DM", SqlDbType.Int, ParameterDirection.Input, ddlTaiLieuID3_DMFNew.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@TaiLieuID4_DM", SqlDbType.Int, ParameterDirection.Input, ddlTaiLieuID4_DMFNew.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@TaiLieuID5_DM", SqlDbType.Int, ParameterDirection.Input, ddlTaiLieuID5_DMFNew.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@TaiLieuID6_DM", SqlDbType.Int, ParameterDirection.Input, ddlTaiLieuID6_DMFNew.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@SoHieu", SqlDbType.NVarChar, ParameterDirection.Input, txtSoHieu.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenTaiLieu", SqlDbType.NVarChar, ParameterDirection.Input, txtTenTaiLieu.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@NgayBanHanh", SqlDbType.NVarChar, ParameterDirection.Input, MyConvert.ToDateFromV_Nullable(dtpDateNew.Text.Trim())));
                arrParams.Add(SqlHelper.CreateParameterObject("@HieuLucTu", SqlDbType.NVarChar, ParameterDirection.Input, MyConvert.ToDateFromV_Nullable(dtpFromDateNew.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@HieuLucDen", SqlDbType.NVarChar, ParameterDirection.Input, MyConvert.ToDateFromV_Nullable(dtpToDateNew.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@TrichYeu", SqlDbType.NVarChar, ParameterDirection.Input, txtTrichYeu.Value));
                arrParams.Add(SqlHelper.CreateParameterObject("@NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, txtNoiDung.Value));
                arrParams.Add(SqlHelper.CreateParameterObject("@FileDinhKem", SqlDbType.NVarChar, ParameterDirection.Input, FilePath));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userID"]));
                if (SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams) > 0)
                {
                    MyCommon.AddMessage(this.Master, "Đã thêm mới thành công tài liệu !", MyConst.MessageType.Success);
                }
            }
            catch (Exception ex)
            {
                MyCommon.AddMessage(this.Master, "Lỗi trong quá trình thêm mới !", MyConst.MessageType.Error);
            }

        }

        protected void UpdateData(int ID)
        {
            try
            {
                string sql = "UPDATE dbo.tblTaiLieu SET SoHieu = @SoHieu,TenTaiLieu = @TenTaiLieu,NgayBanHanh =@NgayBanHanh," +
                             "HieuLucTu = @HieuLucTu,HieuLucDen = @HieuLucDen,TrichYeu = @TrichYeu,NoiDung = @NoiDung, " +
                             "FileDinhKem = @FileDinhKem, UpdateDate = GETDATE(), UserID = @UserID WHERE IDTaiLieu = @ID";
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@SoHieu", SqlDbType.NVarChar, ParameterDirection.Input, txtSoHieu.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenTaiLieu", SqlDbType.NVarChar, ParameterDirection.Input, txtTenTaiLieu.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@NgayBanHanh", SqlDbType.NVarChar, ParameterDirection.Input, MyConvert.ToDateFromV_Nullable(dtpDateNew.Text.Trim())));
                arrParams.Add(SqlHelper.CreateParameterObject("@HieuLucTu", SqlDbType.NVarChar, ParameterDirection.Input, MyConvert.ToDateFromV_Nullable(dtpFromDateNew.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@HieuLucDen", SqlDbType.NVarChar, ParameterDirection.Input, MyConvert.ToDateFromV_Nullable(dtpToDateNew.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@TrichYeu", SqlDbType.NVarChar, ParameterDirection.Input, txtTrichYeu.Value));
                arrParams.Add(SqlHelper.CreateParameterObject("@NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, txtNoiDung.Value));
                arrParams.Add(SqlHelper.CreateParameterObject("@FileDinhKem", SqlDbType.NVarChar, ParameterDirection.Input, FilePath));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userID"]));
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
                if (SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams) > 0)
                {
                    MyCommon.AddMessage(this.Master, "Cập nhật thành công tài liệu !", MyConst.MessageType.Success);
                }
            }
            catch (Exception ex)
            {
                MyCommon.AddMessage(this.Master, "Lỗi trong quá trình cập nhật tài liệu !", MyConst.MessageType.Error);
            }
        }

        protected DataTable GetChiTietTaiLieu(int ID)
        {
            string sql = "SELECT * FROM dbo.tblTaiLieu WHERE IDTaiLieu = @ID";
            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameter);
            return dt;
        }

        protected void LoadControl()
        {
            AIC_PN.Properties.Settings settings = new AIC_PN.Properties.Settings();
            TaiLieuID2_DM.Text = settings.TaiLieuID2_DM;
            TaiLieuID3_DM.Text = settings.TaiLieuID3_DM;
            TaiLieuID4_DM.Text = settings.TaiLieuID4_DM;
            TaiLieuID5_DM.Text = settings.TaiLieuID5_DM;
            TaiLieuID6_DM.Text = settings.TaiLieuID6_DM;
            lblTaiLieuD2_DMNew.Text = settings.TaiLieuID2_DM;
            lblTaiLieuD3_DMNew.Text = settings.TaiLieuID3_DM;
            lblTaiLieuD4_DMNew.Text = settings.TaiLieuID4_DM;
            lblTaiLieuD5_DMNew.Text = settings.TaiLieuID5_DM;
            lblTaiLieuD6_DMNew.Text = settings.TaiLieuID6_DM;
            LoadCombobox(ddlTaiLieuID2_DMF, "TaiLieuID2_DM");
            LoadCombobox(ddlTaiLieuID3_DMF, "TaiLieuID3_DM");
            LoadCombobox(ddlTaiLieuID4_DMF, "TaiLieuID4_DM");
            LoadCombobox(ddlTaiLieuID5_DMF, "TaiLieuID5_DM");
            LoadCombobox(ddlTaiLieuID6_DMF, "TaiLieuID6_DM");
            LoadCombobox(ddlTaiLieuID1_DMFNew, "TaiLieuID1_DM");
            LoadCombobox(ddlTaiLieuID2_DMFNew, "TaiLieuID2_DM");
            LoadCombobox(ddlTaiLieuID3_DMFNew, "TaiLieuID3_DM");
            LoadCombobox(ddlTaiLieuID4_DMFNew, "TaiLieuID4_DM");
            LoadCombobox(ddlTaiLieuID5_DMFNew, "TaiLieuID5_DM");
            LoadCombobox(ddlTaiLieuID6_DMFNew, "TaiLieuID6_DM");
        }

        protected void LoadCombobox(DropDownList dropdown, string MaDM)
        {
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblDanhMuc WHERE MaDM LIKE '" + MaDM + "'");
            if (dt.Rows.Count > 0)
            {
                dropdown.DataSource = dt;
                dropdown.DataTextField = "TenDM";
                dropdown.DataValueField = "ID";
                dropdown.DataBind();
                dropdown.Items.Insert(0, new ListItem("Chọn tiêu chí", "0"));
            }
        }

        protected void BindDataToGrid()
        {
            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@TaiLieuID1_DM", SqlDbType.Int, ParameterDirection.Input, LoaiVanBan));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblTaiLieu WHERE TaiLieuID1_DM = @TaiLieuID1_DM OR @TaiLieuID1_DM = -1",lstParameter);

            grdDanhMuc.DataSource = dt;
            grdDanhMuc.DataBind();

        }

        private string UploadFile()
        {
            try
            {
                if (fulTaiLieu.HasFile)
                {
                    if (fulTaiLieu.PostedFile.ContentLength < 2100000)
                    {
                        string sFolderPath = Server.MapPath(@"userfiles/VanBan");
                        HttpPostedFile myFile = fulTaiLieu.PostedFile;
                        string sFileName = myFile.FileName;
                        string[] arrFileName = sFileName.Split('.');
                        arrFileName[0] = DateTime.Now.ToString("ddMMyyhhssmm");
                        sFileName = arrFileName[0] + "." + arrFileName[1];
                        myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                        return "userfiles/VanBan/" + sFileName;
                    }
                    else
                    {
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (Request.QueryString["ID"] != null)
            {
                LoaiVanBan = Convert.ToInt32(Request.QueryString["ID"]);
            }
            if (!IsPostBack)
            {
                LoadControl();
                BindDataToGrid();
            }
        }



        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }

        protected void grdDanhMuc_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            ID = Convert.ToInt32(e.CommandArgument);


            if (e.CommandName == MyConst.Action.Update)
            {
                formUpdate.Visible = true;
                DataTable arrTaiLieu = GetChiTietTaiLieu(ID);
                txtSoHieu.Text = arrTaiLieu.Rows[0]["SoHieu"].ToString();
                txtTenTaiLieu.Text = arrTaiLieu.Rows[0]["TenTaiLieu"].ToString();
                dtpDateNew.Text = arrTaiLieu.Rows[0]["NgayBanHanh"] == System.DBNull.Value ? "" : Convert.ToDateTime(arrTaiLieu.Rows[0]["NgayBanHanh"]).ToString("dd/MM/yyyy");
                dtpFromDateNew.Text = arrTaiLieu.Rows[0]["HieuLucTu"] == System.DBNull.Value ? "" : Convert.ToDateTime(arrTaiLieu.Rows[0]["HieuLucTu"]).ToString("dd/MM/yyyy");
                dtpToDateNew.Text = arrTaiLieu.Rows[0]["HieuLucDen"] == System.DBNull.Value ? "" : Convert.ToDateTime(arrTaiLieu.Rows[0]["HieuLucDen"]).ToString("dd/MM/yyyy");
                ddlTaiLieuID1_DMFNew.SelectedValue = arrTaiLieu.Rows[0]["TaiLieuID1_DM"].ToString();
                ddlTaiLieuID2_DMFNew.SelectedValue = arrTaiLieu.Rows[0]["TaiLieuID2_DM"].ToString();
                ddlTaiLieuID3_DMFNew.SelectedValue = arrTaiLieu.Rows[0]["TaiLieuID3_DM"].ToString();
                ddlTaiLieuID4_DMFNew.SelectedValue = arrTaiLieu.Rows[0]["TaiLieuID4_DM"].ToString();
                ddlTaiLieuID5_DMFNew.SelectedValue = arrTaiLieu.Rows[0]["TaiLieuID5_DM"].ToString();
                ddlTaiLieuID6_DMFNew.SelectedValue = arrTaiLieu.Rows[0]["TaiLieuID6_DM"].ToString();
                if (arrTaiLieu.Rows[0]["FileDinhKem"].ToString() != "")
                    lbtFileDinhkem.Text = arrTaiLieu.Rows[0]["FileDinhKem"].ToString().Split('/')[2];
                FilePath = arrTaiLieu.Rows[0]["FileDinhKem"].ToString();
                txtTrichYeu.Value = arrTaiLieu.Rows[0]["TrichYeu"].ToString();
                txtNoiDung.Value = arrTaiLieu.Rows[0]["NoiDung"].ToString();
                btnLuu.CommandName = MyConst.Action.Update;
            }
            else if (e.CommandName == MyConst.Action.Delete)
            {
                string sql = "DELETE FROM dbo.tblTaiLieu WHERE IDTaiLieu = @ID";
                List<SqlParameter> lstParameter = new List<SqlParameter>();
                lstParameter.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, lstParameter);
                BindDataToGrid();
                MyCommon.AddMessage(this.Page.Master, "Xóa thành công !", MyConst.MessageType.Success);
            }
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                string temFilePath = UploadFile();
                if (temFilePath != "")
                    FilePath = temFilePath;

                int UserID = Convert.ToInt32(Session["userid"]);
                if (btnLuu.CommandName == MyConst.Action.Addnew)
                {
                    InsertData();
                    BindDataToGrid();
                }
                else if (btnLuu.CommandName == MyConst.Action.Update)
                {
                    UpdateData(ID);
                    BindDataToGrid();
                }
                formUpdate.Visible = false;
            }
            catch (Exception)
            {
                MyCommon.AddMessage(this.Page.Master, "Lỗi hệ thống !", MyConst.MessageType.Error);
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = false;
        }

        protected void btnThem_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            btnLuu.CommandName = MyConst.Action.Addnew;
            Reset();
        }

        protected void Reset()
        {
            txtSoHieu.Text = "";
            txtTenTaiLieu.Text = "";
            dtpDateNew.Text = "";
            dtpFromDateNew.Text = "";
            dtpToDateNew.Text = "";
            txtTrichYeu.Value = "";
            txtNoiDung.Value = "";
            lbtFileDinhkem.Text = "";
        }

        protected void lbtFileDinhkem_Click(object sender, EventArgs e)
        {
            if (lbtFileDinhkem.Text.Length != 0)
            {
                string FileName = lbtFileDinhkem.Text;
                MyCommon.Download(FileName, "userfiles/VanBan/" + FileName);
            }
        }

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            string BanHanhFrom = dtpBanHanhFrom.Text;
            string BanHanhTo = dtpBanHanhTo.Text;
            string TuNgay = dtpFromDate.Text;
            string DenNgay = dtpToDate.Text;
            string SoHieu = chkSoHieu.Checked ? txtSearch.Text : "";
            string TenTaiLieu = chkTenTaiLieu.Checked ? txtSearch.Text : "";
            string TrichYeu = chkTrichYeu.Checked ? txtSearch.Text : "";
            string NoiDung = chkNoiDung.Checked ? txtSearch.Text : "";
            string sql = "SELECT * FROM dbo.tblTaiLieu " +
                         "WHERE ((SoHieu LIKE N'%'+@SoHieu+'%' AND @SoHieu = '')" +
                         "OR (TenTaiLieu LIKE N'%'+@TenTaiLieu+'%' AND @TenTaiLieu = '')" +
                         "OR (TrichYeu LIKE N'%'+@TrichYeu+'%' AND @TrichYeu = '')" +
                         "OR (NoiDung LIKE N'%'+@NoiDung+'%' AND @NoiDung = ''))" +
                         "AND (NgayBanHanh >= CONVERT(DATETIME,@BanHanhFrom,103) AND @BanHanhFrom = '') " +
                         "AND (NgayBanHanh <= CONVERT(DATETIME,@BanHanhTo,103) AND @BanHanhTo = '') " +
                         "AND (HieuLucTu >= CONVERT(DATETIME,@TuNgay,103) AND @TuNgay = '') " +
                         "AND (HieuLucDen <= CONVERT(DATETIME,@DenNgay,103) AND @DenNgay = '') " +
                         "AND TaiLieuID1_DM = @LoaiVanBan";
            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@SoHieu", SqlDbType.NVarChar, ParameterDirection.Input, SoHieu));
            lstParameter.Add(SqlHelper.CreateParameterObject("@TenTaiLieu", SqlDbType.NVarChar, ParameterDirection.Input, TenTaiLieu));
            lstParameter.Add(SqlHelper.CreateParameterObject("@TrichYeu", SqlDbType.NVarChar, ParameterDirection.Input, TrichYeu));
            lstParameter.Add(SqlHelper.CreateParameterObject("@NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, NoiDung));
            lstParameter.Add(SqlHelper.CreateParameterObject("@BanHanhFrom", SqlDbType.NVarChar, ParameterDirection.Input, BanHanhFrom));
            lstParameter.Add(SqlHelper.CreateParameterObject("@BanHanhTo", SqlDbType.NVarChar, ParameterDirection.Input, BanHanhTo));
            lstParameter.Add(SqlHelper.CreateParameterObject("@TuNgay", SqlDbType.NVarChar, ParameterDirection.Input, TuNgay));
            lstParameter.Add(SqlHelper.CreateParameterObject("@DenNgay", SqlDbType.NVarChar, ParameterDirection.Input, DenNgay));
            lstParameter.Add(SqlHelper.CreateParameterObject("@LoaiVanBan", SqlDbType.Int, ParameterDirection.Input, LoaiVanBan));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameter);
            grdDanhMuc.DataSource = dt;
            grdDanhMuc.DataBind();
        }

        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("DanhMucTaiLieu");
            if (Role == null || Role["Xem"] == 0)
            {
                btnThem.Visible = false;
                grdDanhMuc.Columns[grdDanhMuc.Columns.Count - 1].Visible = false;
                grdDanhMuc.Columns[grdDanhMuc.Columns.Count - 2].Visible = false;
            }
            else if (Role["Sua"] == 0)
            {
                btnThem.Visible = false;
                grdDanhMuc.Columns[grdDanhMuc.Columns.Count - 1].Visible = false;
                grdDanhMuc.Columns[grdDanhMuc.Columns.Count - 2].Visible = false;
            }
        }
    }
}
